package cn.javaex.fileupload;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 路径工具类
 */
public class PathUtils {
	
	/**
	 * 判断是否是绝对路径
	 * @param path
	 * @return
	 */
	public static boolean isAbsolutePath(String path) {
		path = path.substring(0, 2);
		return path.startsWith("/") || path.endsWith(":");
	}
	
	/**
	 * 获取项目所在磁盘的文件夹路径
	 * @return
	 */
	public static String getProjectPath() {
		try {
			HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
			// 获取地址内容，原路径（项目名）
			String realPath = request.getSession().getServletContext().getRealPath("/");
			// tomcat webapps下部署
			if (realPath!=null && realPath.length()>0 && realPath.indexOf("apache-tomcat")>0) {
				String path = request.getContextPath();    // 项目名
				path = path.replace("/", File.separator) + File.separator;
				return realPath.replace(path, "");
			}
			
			return System.getProperty("user.dir");
		} catch (Exception e) {
			return System.getProperty("user.dir");
		}
	}
	
	/**
	 * 获取服务路径
	 * @return
	 */
	public static String getServerPath() {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		
		String domain = request.getScheme() + "://" + request.getServerName();
		int port = request.getServerPort();
		
		return port==80 ? domain : domain + ":" + port;
	}

	/**
	 * 处理路径
	 * @param uploadPath
	 * @param dateDirectory 是否根据日期自动创建3级目录
	 */
	public static String processingPath(String uploadPath, boolean dateDirectory) {
		// 路径格式转换
		uploadPath = uploadPath.replace('\\', '/');
		
		// 根据日期自动创建3级目录
		if (dateDirectory) {
			Date date = new Date();
			String dateFolder = new SimpleDateFormat("yyyy/MM/dd").format(date);
			// 设置文件存储目录
			uploadPath = uploadPath + "/" + dateFolder;
		}
		
		// 传入的路径是否是绝对路径
		boolean isAbsolutePath = isAbsolutePath(uploadPath);
		
		// 存储文件的物理路径
		String filePath = "";
		if (isAbsolutePath) {
			filePath = uploadPath;
		} else {
			String projectPath = PathUtils.getProjectPath();
			filePath = projectPath + File.separator + uploadPath;
		}
		
		// 自动创建文件夹
		File f = new File(filePath);
		f.mkdirs();
		
		return uploadPath;
	}

}
